﻿using AutoMapper;
using DLL.NET50.DB.CRUD;
using DLL.NET50.DB.MS.Entity;
using DLL.NET60.DB.MS.Entity.DTO;
using DLL.Standard.Infrastructure.Log;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace DLL.NET.DB.MS.Drugs.CRUD.Repository
{
    public interface IBaseDrugsRepository : IBaseRepository<adi_dic_drug>
    {
        List<DTO_adi_dic_drug> GetDrugs();

        List<DTO_adi_dic_drug> GetDrugs(int Count);

        List<DTO_adi_dic_drug> GetDrugs(Expression<Func<adi_dic_drug, bool>> @where);

        /// <summary>
        /// 查询药品
        /// </summary>
        /// <param name="drugCode"></param>
        /// <param name="pycode"></param>
        /// <param name="drugname"></param>
        /// <returns></returns>
        List<DTO_adi_dic_drug> GetDrugs(string drugCode, string pycode, string drugname);

        List<DTO_adi_dic_drug> SearchDrugsByDrugCode(string drugCode);

        List<DTO_adi_dic_drug> SearchDrugsByPyCode(string pycode);

        List<DTO_adi_dic_drug> SearchDrugsByApprovatNumber(string ApprovalNumber);

        List<DTO_adi_dic_drug> SearchByUniqueCode(string uniqueCode);

        /// <summary>
        /// 查询药品
        /// </summary>
        /// <param name="drugName"></param>
        /// <returns></returns>
        List<DTO_adi_dic_drug> SearchDrugsByName(string drugName);

        bool AddDrug(DTO_adi_dic_drug entity);

        bool AddRangeDrugs(List<DTO_adi_dic_drug> entitysDTO);

        bool UpdateDrug(DTO_adi_dic_drug entity);

        bool UpdateRangeDrugs(List<DTO_adi_dic_drug> entitysDTO);

        bool DeleteDrug(DTO_adi_dic_drug entity);

        bool AddOrModify(DTO_adi_dic_drug entity);

        bool SaveDrug(DTO_adi_dic_drug entityDTO);

        bool IsExist_ByDrugUniqueCode(DTO_adi_dic_drug entityDTO);

        bool MS_SaveDrug(DTO_adi_dic_drug entityDTO);

        bool MS_IsExistByDrugCode(DTO_adi_dic_drug entityDTO);

        bool IsExistByCode(string drugCode);
    }

    public class CBaseDrugsRepository : BaseRepository<adi_dic_drug>, IBaseDrugsRepository
    {
        private IMapper _mapper;

        public CBaseDrugsRepository(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork.Db)
        {
            _mapper = mapper;
        }

        //获取药品
        public List<DTO_adi_dic_drug> GetDrugs()
        {
            try
            {
                var dic = GetAllNoTracking().Include(p => p.flush_Groups)
                    .ThenInclude(fp => fp.flush_Params)
                    .Include(p => p.flush_Groups)
                    .ThenInclude(fp => fp.pumpBack_Params).ToList();

                List<adi_dic_drug> ls = dic;

                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic.ToList());
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行获取药品字典信息出现异常：" + ex.Message);
            }
            return new List<DTO_adi_dic_drug>();
        }

        public List<DTO_adi_dic_drug> GetDrugs(int Count)
        {
            try
            {
                Expression<Func<adi_dic_drug, bool>> where1 = s => s.SOLVENT_FLAG != null;
                Expression<Func<adi_dic_drug, string>> order = o => o.PY_CODE;
                var dic = GetPageList(where1, order, 1, Count, false, false).ToList();

                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic.ToList());
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行获取药品字典信息出现异常：" + ex.Message);
            }
            return new List<DTO_adi_dic_drug>();
        }

        public List<DTO_adi_dic_drug> GetDrugs(Expression<Func<adi_dic_drug, bool>> @where)
        {
            try
            {
                List<adi_dic_drug> dic = Where<string>(where, o => o.PY_CODE).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params).ToList();
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行获取药品字典信息出现异常：" + ex.Message);
            }
            return new List<DTO_adi_dic_drug>();
        }

        public List<DTO_adi_dic_drug> GetDrugs(string drugCode, string pycode, string drugname)
        {
            try
            {
                //1.Linq to Entities
                if (drugCode != null)
                {
                    if (drugCode.Length > 0)
                    {
                        return SearchDrugsByDrugCode(drugCode);
                    }
                }
                if (pycode != null)
                {
                    if (pycode.Length > 0)
                    {
                        Expression<Func<adi_dic_drug, bool>> where = c => c.PY_CODE.Contains(pycode);
                        Expression<Func<adi_dic_drug, string>> order = o => o.PY_CODE;
                        IQueryable<adi_dic_drug> dic = Where<string>(where, order).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                        List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                        return dTOs;
                    }
                }
                if (drugname != null)
                {
                    if (drugname.Length > 0)
                    {
                        Expression<Func<adi_dic_drug, bool>> where = c => c.DRUG_NAME.Contains(drugname);
                        Expression<Func<adi_dic_drug, string>> order = o => o.DRUG_NAME;
                        IQueryable<adi_dic_drug> dic = Where<string>(where, order).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                        List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                        return dTOs;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行查询药品字典信息出现异常：" + ex.Message);
            }
            return new List<DTO_adi_dic_drug>();
        }

        public List<DTO_adi_dic_drug> SearchDrugsByDrugCode(string drugCode)
        {
            try
            {
                var dic = Where(c => c.DRUG_CODE.Trim() == drugCode.Trim()).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                List<adi_dic_drug> drugs = dic.ToList();
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return new List<DTO_adi_dic_drug>();
            }
        }

        public List<DTO_adi_dic_drug> SearchDrugsByPyCode(string pycode)
        {
            try
            {
                var dic = Where(c => c.PY_CODE.Contains(pycode)).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return new List<DTO_adi_dic_drug>();
            }
        }

        public List<DTO_adi_dic_drug> SearchDrugsByApprovatNumber(string ApprovalNumber)
        {
            try
            {
                var dic = Where(c => c.ApprovalNumber.Contains(ApprovalNumber)).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return new List<DTO_adi_dic_drug>();
            }
        }

        public List<DTO_adi_dic_drug> SearchByUniqueCode(string uniqueCode)
        {
            try
            {
                var dic = Where(c => c.Drug_UniqueCode == uniqueCode).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return new List<DTO_adi_dic_drug>();
            }
        }

        public List<DTO_adi_dic_drug> SearchDrugsByName(string drugName)
        {
            try
            {
                var dic = Where(c => c.DRUG_NAME.Contains(drugName)).Include(p => p.flush_Groups).ThenInclude(fp => fp.flush_Params).Include(p => p.flush_Groups).ThenInclude(fp => fp.pumpBack_Params);
                List<DTO_adi_dic_drug> dTOs = _mapper.Map<List<DTO_adi_dic_drug>>(dic);
                return dTOs;
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
            }
            return new List<DTO_adi_dic_drug>();
        }

        public bool IsExist_ByDrugUniqueCode(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                string uniqueCode = entityDTO.Drug_UniqueCode;
                if (entityDTO.Drug_UniqueCode.Length == 0)
                {
                    entityDTO.SetFlushParamUniqueCode();
                }
                List<adi_dic_drug> lud = Where(p => p.Drug_UniqueCode == uniqueCode).ToList();
                if (lud != null)
                {
                    if (lud.Count == 0)
                    {
                        //不存在该药
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return false;
            }
        }

        public bool IsExistByCode(string drugCode)
        {
            List<DTO_adi_dic_drug> drugs = SearchDrugsByDrugCode(drugCode);
            if (drugs.Count > 0)
            { return true; }
            else
            {
                return false;
            }
        }

        public bool MS_IsExistByDrugCode(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                string uniqueCode = entityDTO.Drug_UniqueCode;
                if (entityDTO.Drug_UniqueCode.Length == 0)
                {
                    entityDTO.SetFlushParamUniqueCode();
                }
                string drugCode = entityDTO.DRUG_CODE;
                List<adi_dic_drug> lud = Where(p => p.DRUG_CODE == drugCode).ToList();
                if (lud != null)
                {
                    if (lud.Count == 0)
                    {
                        //不存在该药
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
                return false;
            }
        }

        public bool SaveDrug(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                if (entityDTO.Drug_UniqueCode.Length == 0)
                {
                    entityDTO.SetFlushParamUniqueCode();
                }
                bool exist = IsExist_ByDrugUniqueCode(entityDTO);
                if (true == exist)
                {
                    //存在
                    UpdateDrug(entityDTO);
                }
                else
                {
                    AddDrug(entityDTO);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
            }

            return true;
        }

        public bool MS_SaveDrug(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                if (entityDTO.Drug_UniqueCode.Length == 0)
                {
                    entityDTO.SetFlushParamUniqueCode();
                }
                bool exist = MS_IsExistByDrugCode(entityDTO);
                if (true == exist)
                {
                    //该药品编码存在
                    List<DTO_adi_dic_drug> drugs = SearchDrugsByDrugCode(entityDTO.DRUG_CODE);
                    if (drugs.Count > 0)
                    {
                        if (drugs[0].Drug_UniqueCode == entityDTO.Drug_UniqueCode)
                        {
                            UpdateDrug(entityDTO);
                        }
                        else
                        {
                            //存在相同的药品编码，但drug unique code 不一样，则删除老的，
                            DeleteDrug(drugs[0]);
                            AddDrug(entityDTO);
                        }
                    }
                }
                else
                {
                    //本地不存在该药品编码，但要判断，本地是否存在相同的drug unique code 的
                    bool isExist = IsExist_ByDrugUniqueCode(entityDTO);
                    if ((false == isExist))
                    {
                        //本地不存在相同唯一码的药
                        AddDrug(entityDTO);
                    }
                    else
                    {
                        LogHelper.Warn("本地存在药品名称相同，厂家相同，计量相同的药，无法保存");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
            }

            return true;
        }

        //添加
        public bool AddDrug(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                adi_dic_drug entity = _mapper.Map<adi_dic_drug>(entityDTO);
                base.Add(entity);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行插入药品字典出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public bool AddRangeDrugs(List<DTO_adi_dic_drug> entitysDTO)
        {
            try
            {
                List<adi_dic_drug> entitys = _mapper.Map<List<adi_dic_drug>>(entitysDTO);
                base.AddRange(entitys);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行插入药品字典出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        //删除
        public bool DeleteDrug(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                adi_dic_drug entity = _mapper.Map<adi_dic_drug>(entityDTO);
                base.Remove(entity);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行删除药品字典信息出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public bool DeleteRange(List<DTO_adi_dic_drug> entitysDTO)
        {
            try
            {
                List<adi_dic_drug> entitys = _mapper.Map<List<adi_dic_drug>>(entitysDTO);
                base.RemoveRange(entitys);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行删除药品字典信息出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        //修改
        public bool UpdateDrug(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                adi_dic_drug entity = _mapper.Map<adi_dic_drug>(entityDTO);
                base.Update(entity);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行更新药品字典出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public bool UpdateRangeDrugs(List<DTO_adi_dic_drug> entitysDTO)
        {
            try
            {
                List<adi_dic_drug> entitys = _mapper.Map<List<adi_dic_drug>>(entitysDTO);
                base.UpdateRange(entitys);
            }
            catch (Exception ex)
            {
                LogHelper.Warn("执行更新药品字典出现异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public bool AddOrModify(DTO_adi_dic_drug entityDTO)
        {
            try
            {
                adi_dic_drug entity = _mapper.Map<adi_dic_drug>(entityDTO);
                string drugCode = entity.DRUG_CODE;
                List<DTO_adi_dic_drug> ld = SearchDrugsByPyCode(drugCode);
                if (ld.Count == 0)
                {
                    //不存在，在添加
                    base.Add(entity);
                }
                else if (ld.Count == 1)
                {
                    //存在，则修改
                    Update(entity);
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn("adi_dic_drug执行指令出现异常：" + ex.Message);
            }

            return true;
        }

        //执行SQLCOMMAND 命令
    }
}